/**
 * Notes: 工作流模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2023-08-12 07:48:00  
 */

const BaseProjectService = require('./base_project_service.js');
const util = require('../../../framework/helpers/util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');
const dataUtil = require('../../../framework/helpers/data_util.js');
const timeUtil = require('../../../framework/helpers/time_util.js');
const FlowModel = require('../config/models_config').flow_model;
const UserModel = require('../config/models_config').user_model;
const MsgService = require('./msg_service.js');


class FlowService extends BaseProjectService {

	// 审批通知
	async sendCheckMsg(flowId) {
		if (!flowId) return;

		let where = {
			_id: flowId
		}
		let flow = await FlowModel.getOne(where);
		if (!flow) return;

		// 获取待审批人员名单
		let whereUser = {
			USER_STATUS: 1,
			USER_AUTH: 1, // 有审批权限
			USER_DEPT: flow.FLOW_TO_DEPT
		}
		let userList = await UserModel.getAll(whereUser);
		if (!userList || userList.length == 0) return;

		// 构建通知内容
		let title = flow.FLOW_OBJ.title || flow.FLOW_CATE_NAME;
		let content = `您有新的【${flow.FLOW_CATE_NAME}】需要审批，申请人：${flow.FLOW_OBJ.person || flow.FLOW_USER_NAME}，编号：${flow.FLOW_NO}`;

		// 推送通知 
		let msgService = new MsgService();
		for (let k = 0; k < userList.length; k++) {
			let userId = userList[k].USER_MINI_OPENID;
			await msgService.insertMsg({
				title,
				content,
				type: 'check',
				formId: flowId,
				userId,
				userType: 'user'
			});
		}
	}

	getFlowPrefix(step) {
		return 'FLOW' + step;
	}


	async getFlowDetail(userId, id) {
		try {
			console.log('[Flow Service] 获取流程详情:', id);
			
			// 特殊处理：如果ID为对象，尝试提取_id
			if (typeof id === 'object' && id._id) {
				id = id._id;
				console.log('[Flow Service] ID是对象格式，提取后的ID:', id);
			}
			
			if (!id) {
				console.error('[Flow Service] 未提供有效ID');
				this.AppError('未找到流程ID');
			}
			
			let where = {
				_id: id
			};
			
			console.log('[Flow Service] 查询条件:', JSON.stringify(where));
			let flow = await FlowModel.getOne(where);
			
			if (!flow) {
				console.error('[Flow Service] 未找到流程数据');
				return null;
			}
			
			// 基本字段检查与补充
			// 确保流程步骤字段存在
			if (!flow.FLOW_STEP) {
				// 尝试从FLOW_LIST复制数据
				if (flow.FLOW_LIST && Array.isArray(flow.FLOW_LIST)) {
					flow.FLOW_STEP = [...flow.FLOW_LIST];
					console.log('[Flow Service] 从FLOW_LIST复制数据到FLOW_STEP');
				} else {
					flow.FLOW_STEP = [];
					console.warn('[Flow Service] FLOW_STEP字段不存在，初始化为空数组');
				}
			}
			
			// 确保FLOW_OBJ字段存在
			if (!flow.FLOW_OBJ) {
				flow.FLOW_OBJ = {};
				console.warn('[Flow Service] FLOW_OBJ不存在，创建默认对象');
			}
			
			// 确保基础字段存在
			flow.FLOW_USER = flow.FLOW_USER || flow.FLOW_USER_NAME || '';
			flow.FLOW_TITLE = flow.FLOW_TITLE || flow.FLOW_OBJ.title || flow.FLOW_CATE_NAME || '';
			flow.FLOW_OBJ_URL = flow.FLOW_OBJ_URL || '';
			flow.FLOW_OBJ_CONTENT = flow.FLOW_OBJ_CONTENT || '';
			
			// 日期处理
			if (!flow.FLOW_TITLE_TIME && flow.FLOW_ADD_TIME) {
				const timeUtil = require('../../../framework/helpers/time_util.js');
				flow.FLOW_TITLE_TIME = timeUtil.timestamp2Time(flow.FLOW_ADD_TIME, 'Y-M-D');
			}
			
			console.log('[Flow Service] 获取流程详情成功');
			return flow;
		} catch (err) {
			console.error('[Flow Service] 获取流程详情错误:', err);
			throw err;
		}
	}

	// 查看流程
	async viewFlow(userId, {
		id,
		hasImageForms
	}) {
		console.log('[Flow] 查看流程开始, ID:', id, '用户ID:', userId);
		
		// 特殊处理：如果ID为对象，尝试提取_id
		if (typeof id === 'object' && id._id) {
			id = id._id;
			console.log('[Flow] ID是对象格式，提取后的ID:', id);
		}
		
		if (!id) {
			console.error('[Flow] 查看流程失败: 未提供有效ID');
			this.AppError('未找到流程ID');
		}

		// 查询条件
		let where = {
			_id: id
		};
		
		// 添加用户ID作为备用查询条件，提高匹配概率
		let backupWhere = {
			$or: [
				{ FLOW_USER_ID: userId },
				{ FLOW_MID: userId }
			]
		};
		
		let fields = '*';

		// 图片链接表单值处理
		if (hasImageForms) fields += ',FLOW_FORMS_PIC';

		try {
			// 查询记录
			console.log('[Flow] 查询流程条件:', JSON.stringify(where));
			let flow = await FlowModel.getOne(where, fields);
			
			// 如果找不到，尝试使用备用条件
			if (!flow) {
				console.log('[Flow] 主查询未找到记录，尝试使用备用条件:', JSON.stringify(backupWhere));
				let flows = await FlowModel.getAll(backupWhere, fields, { FLOW_ADD_TIME: 'desc' }, 1);
				
				if (flows && flows.length > 0) {
					flow = flows[0];
					console.log('[Flow] 使用备用条件找到流程:', flow._id);
				}
			}
			
			if (!flow) {
				console.error('[Flow] 查看流程失败: 流程不存在');
				this.AppError('流程不存在或已被删除');
			}
			
			console.log('[Flow] 找到流程:', flow._id);

			// 增加用户信息判断
			flow.IS_USER = (userId == flow.FLOW_USER_ID || userId == flow.FLOW_MID) ? true : false;

			return flow;
		} catch (err) {
			console.error('[Flow] 查看流程出错:', err);
			this.AppError('流程查询失败: ' + (err.message || '未知错误'));
		}
	}

	/**添加申请数据 */
	async insertFlow(userId, {
		cateId,
		cateName,
		depts,
		forms
	}) {
		try {
			console.log('[Flow] 收到提交请求，表单数据:', JSON.stringify({ cateId, cateName, depts, forms }));
			
			// 获取用户信息
			let user = await UserModel.getOne({ USER_MINI_OPENID: userId, USER_STATUS: 1 });
			if (!user) this.AppError('用户不存在');

			// 数据校验
			if (!forms) this.AppError('表单数据不能为空');
			if (!Array.isArray(forms)) {
				console.log('[Flow] 表单数据不是数组:', typeof forms);
				// 尝试修复数据格式
				if (typeof forms === 'object') {
					forms = Object.values(forms);
					console.log('[Flow] 修复后的表单数据:', JSON.stringify(forms));
				} else {
					this.AppError('表单信息格式错误');
				}
			}
			if (forms.length === 0) this.AppError('表单不能为空');
			
			if (!cateId) this.AppError('分类不存在');
			if (!depts || !Array.isArray(depts) || depts.length == 0) this.AppError('审批流程配置错误');

			// 获取题目和说明等表单信息
			let title = '';
			let desc = '';
			let person = '';
			let phone = '';

			for (let k = 0; k < forms.length; k++) {
				if (forms[k].mark == 'title') title = forms[k].val;
				if (forms[k].mark == 'desc') desc = forms[k].val;
				if (forms[k].mark == 'person') person = forms[k].val;
				if (forms[k].mark == 'phone') phone = forms[k].val;
			}

			// 如果没有提供标题，自动生成标题
			if (!title) {
				console.log('[Flow] 未提供标题，自动生成标题');
				
				// 查找特定表单字段作为标题成分
				let startDate = '';
				let endDate = '';
				
				for (let k = 0; k < forms.length; k++) {
					if (forms[k].mark == 'start') startDate = forms[k].val;
					if (forms[k].mark == 'end') endDate = forms[k].val;
				}
				
				// 构建标题：请假类型 + 申请人 + 日期
				title = cateName || '审批流程';
				
				if (person) {
					title += ' - ' + person;
				} else if (user.USER_NAME) {
					title += ' - ' + user.USER_NAME;
				}
				
				if (startDate) {
					title += ' (' + startDate;
					if (endDate && endDate !== startDate) {
						title += ' 至 ' + endDate;
					}
					title += ')';
				}
				
				console.log('[Flow] 自动生成的标题:', title);
				
				// 添加生成的标题到表单中
				forms.push({
					mark: 'title',
					title: '标题',
					type: 'text',
					val: title
				});
			}

			// 获取流程编号
			let where = {
				_pid: this.getProjectId(),
			};
			let flowCnt = await FlowModel.count(where);
			let flowNo = flowCnt + 1;

			// 提取表单里的基本数据
			let flowObj = {
				title, // 标题
				desc, // 说明
				person, // 提交人
				phone, // 提交人电话等信息
			};

			let data = {
				FLOW_NO: flowNo,
				FLOW_CATE_ID: cateId,
				FLOW_CATE_NAME: cateName,
				FLOW_STATUS: FlowModel.STATUS.RUN,
				FLOW_DEPTS: depts,

				FLOW_USER_ID: userId,
				FLOW_USER_NAME: user.USER_NAME,
				FLOW_USER_DEPT: user.USER_DEPT,
				FLOW_FORMS: forms,
				FLOW_OBJ: flowObj,
				FLOW_TIME: this._timestamp,

				FLOW_TO_DEPT: depts[0],
				FLOW_TO_NATIVE_DEPT: depts[0],
				FLOW_TO_STEP: 0,

				FLOW_NOW_STEP: 0,
				FLOW_NOW_DEPT: user.USER_DEPT,
				FLOW_NOW_NATIVE_DEPT: user.USER_DEPT,
				FLOW_NOW_USER_NAME: user.USER_NAME,
				FLOW_NOW_USER_ID: userId,
				FLOW_NOW_STATE: 1,

				FLOW_LIST: [],
				FLOW_DAY: timeUtil.time('Y-M-D'),
				FLOW_ADD_TIME: this._timestamp,
				FLOW_MID: userId, // FLOW_MID字段已添加到模型定义中
			};

			// 插入数据
			let id = await FlowModel.insert(data);
			console.log('[Flow] 审批流程创建成功，ID:', id, '状态:', data.FLOW_STATUS, '当前步骤:', data.FLOW_NOW_STEP);

			// 验证ID是否有效
			if (!id) {
				console.error('[Flow] 审批流程创建失败，未返回有效ID');
				this.AppError('审批流程创建失败');
			}

			// 再次查询确认数据已写入
			let checkFlow = await FlowModel.getOne({ _id: id });
			if (!checkFlow) {
				console.error('[Flow] 审批流程创建后无法查询到数据');
				this.AppError('审批流程创建后无法验证');
			}

			// 发送审批通知
			try {
				await this.sendCheckMsg(id);
			} catch (err) {
				console.error('[Flow] 发送审批通知失败:', err);
				// 继续流程，不阻断
			}

			return {
				id
			};
		} catch (err) {
			console.error('[Flow] 创建审批流程错误:', err);
			throw err;
		}
	}

	/**修改申请 */
	async editFlow(userId, data) {
		try {
			// 确保接收到的是对象，兼容不同的调用方式
			let { id, forms } = data || {};
			
			console.log('[Flow] 收到修改请求，原始数据:', JSON.stringify(data));
			console.log('[Flow] 解析后数据 - ID:', id, '用户ID:', userId);
			
			// 数据校验
			if (!id) {
				// 尝试从整个对象中获取id
				if (data.id) {
					id = data.id;
					console.log('[Flow] 从完整对象中获取ID:', id);
				} else {
					console.error('[Flow] 修改失败: 未提供ID');
					this.AppError('申请单号不存在');
				}
			}

			// 尝试修复ID格式
			if (typeof id === 'object' && id._id) {
				id = id._id;
				console.log('[Flow] 修复ID格式为:', id);
			}
			
			if (!forms || !Array.isArray(forms)) {
				console.error('[Flow] 修改失败: 表单格式错误');
				this.AppError('表单信息错误');
			}

			// 查询流程 - 允许通过FLOW_USER_ID或FLOW_MID查询
			let where = {
				_id: id
			};
			
			console.log('[Flow] 查询流程条件:', JSON.stringify(where));
			
			let flow = await FlowModel.getOne(where);
			if (!flow) {
				// 如果直接查询不到，尝试检查是否有最近创建的流程
				console.log('[Flow] 通过ID查询失败，尝试查询最近创建的流程');
				let altWhere = { 
					$or: [
						{ FLOW_USER_ID: userId },
						{ FLOW_MID: userId }
					]
				};
				
				let flows = await FlowModel.getAll(altWhere, '*', { FLOW_ADD_TIME: 'desc' }, 1);
				if (flows && flows.length > 0) {
					flow = flows[0];
					id = flow._id; // 更新ID为最新流程ID
					console.log('[Flow] 找到最近创建的流程:', flow._id);
				} else {
					console.error('[Flow] 找不到要修改的流程, ID:', id, '用户ID:', userId);
					this.AppError('申请不存在');
				}
			}

			console.log('[Flow] 找到流程:', flow._id, '状态:', flow.FLOW_STATUS, '当前步骤:', flow.FLOW_NOW_STEP);

			// 检查权限 - 只有流程创建者才能修改
			let mine = (userId == flow.FLOW_USER_ID || userId == flow.FLOW_MID);
			if (!mine) {
				console.error('[Flow] 权限错误: 用户无权修改此流程');
				this.AppError('您无权修改此流程');
			}

			// 检查流程状态
			if (flow.FLOW_STATUS != FlowModel.STATUS.RUN) {
				let statusText = '';
				switch (flow.FLOW_STATUS) {
					case FlowModel.STATUS.OVER:
						statusText = '已完成';
						break;
					case FlowModel.STATUS.CANCEL:
						statusText = '已取消';
						break;
					case FlowModel.STATUS.REJECT:
						statusText = '已驳回';
						break;
					default:
						statusText = '未知状态';
				}
				console.error('[Flow] 流程状态不允许修改:', flow.FLOW_STATUS);
				this.AppError(`该流程${statusText}，不能修改`);
			}
			
			if (flow.FLOW_NOW_STEP != 0) {
				console.error('[Flow] 流程当前步骤不允许修改:', flow.FLOW_NOW_STEP);
				this.AppError('该流程已经开始审批，不能修改');
			}

			// 获取题目和说明等表单信息
			let title = '';
			let desc = '';
			let person = '';
			let phone = '';

			for (let k = 0; k < forms.length; k++) {
				if (forms[k].mark == 'title') title = forms[k].val;
				if (forms[k].mark == 'desc') desc = forms[k].val;
				if (forms[k].mark == 'person') person = forms[k].val;
				if (forms[k].mark == 'phone') phone = forms[k].val;
			}

			// 更新流程数据
			let data = {
				FLOW_TITLE: title,
				FLOW_DESC: desc,
				FLOW_FORMS: forms,
				FLOW_UPDATE_TIME: this._timestamp,
				FLOW_UPDATE_IP: this._ip
			};

			await FlowModel.edit(where, data);

			return {
				id: flow._id,
				FLOW_STATUS: flow.FLOW_STATUS
			};

		} catch (err) {
			console.error('[Flow] 修改流程出错:', err);
			throw err;
		}
	}


	/**逐级审批*/
	async stepFlow(userId, {
		id,
		forms,
		state
	}) { 
		// 数据校验
		if (!id) this.AppError('单号不存在');
		if (!Array.isArray(forms)) this.AppError('表单信息错误');
		
		// 状态判断 1=通过 8=驳回
		state = Number(state);
		if (state != 1 && state != 8) state = 1;

		// 获取我的身份
		let user = await UserModel.getOne({ USER_MINI_OPENID: userId, USER_STATUS: 1, USER_AUTH: 1 });
		if (!user) this.AppError('您没有审批权限');

		// 查询流程
		let where = {
			_id: id
		}
		let flow = await FlowModel.getOne(where);
		if (!flow) this.AppError('流程不存在');

		// 判断审批权限
		if (user.USER_DEPT != flow.FLOW_TO_DEPT) 
			this.AppError('您没有审批权限，当前审批部门是：' + flow.FLOW_TO_DEPT);

		if (flow.FLOW_STATUS != FlowModel.STATUS.RUN) this.AppError('该流程已经结束');

		// 获取意见
		let desc = '';
		for (let k = 0; k < forms.length; k++) {
			if (forms[k].mark == 'desc') desc = forms[k].val;
		}
		
		// 数据提取
		let flowDATA = {};
		let depts = flow.FLOW_DEPTS;
		let step = flow.FLOW_TO_STEP; //待审批的步骤

		let list = dataUtil.deepClone(flow.FLOW_LIST);
		list.push({
			step,
			dept: user.USER_DEPT,
			nativeDept: user.USER_DEPT,
			forms,
			time: this._timestamp,
			userId,
			userName: user.USER_NAME,
			state
		});

		flowDATA.FLOW_LIST = list;

		// 驳回
		if (state == 8) {
			flowDATA.FLOW_STATUS = FlowModel.STATUS.REJECT;
			flowDATA.FLOW_NOW_STEP = step;
			flowDATA.FLOW_NOW_DEPT = user.USER_DEPT;
			flowDATA.FLOW_NOW_NATIVE_DEPT = user.USER_DEPT;
			flowDATA.FLOW_NOW_USER_NAME = user.USER_NAME;
			flowDATA.FLOW_NOW_USER_ID = userId;
			flowDATA.FLOW_NOW_STATE = 8;
			flowDATA.FLOW_TO_DEPT = '';
			flowDATA.FLOW_TO_NATIVE_DEPT = '';
			flowDATA.FLOW_TO_STEP = -1;

			await FlowModel.edit(where, flowDATA);
			return {
				type: 'reject'
			};
		}

		// 通过 且有下一步骤
		let nextStep = step + 1;
		if (nextStep < depts.length) {
			let nextDept = depts[nextStep]; //下一审批部门

			flowDATA.FLOW_STATUS = FlowModel.STATUS.RUN;
			flowDATA.FLOW_NOW_STEP = step;
			flowDATA.FLOW_NOW_DEPT = user.USER_DEPT;
			flowDATA.FLOW_NOW_NATIVE_DEPT = user.USER_DEPT;
			flowDATA.FLOW_NOW_USER_NAME = user.USER_NAME;
			flowDATA.FLOW_NOW_USER_ID = userId;
			flowDATA.FLOW_NOW_STATE = 1;
			flowDATA.FLOW_TO_DEPT = nextDept;
			flowDATA.FLOW_TO_NATIVE_DEPT = nextDept;
			flowDATA.FLOW_TO_STEP = nextStep;

			await FlowModel.edit(where, flowDATA);

			// 发送审批通知
			await this.sendCheckMsg(id);

			return {
				type: 'wait',
				dept: nextDept
			};
		}

		// 检查是否已经通过研发经理和董事长的审批
		let hasDevManagerApproval = false;
		let hasCEOApproval = false;
		
		for (let item of list) {
			if (item.dept === '研发经理' && item.state === 1) {
				hasDevManagerApproval = true;
			}
			if (item.dept === '董事长' && item.state === 1) {
				hasCEOApproval = true;
			}
		}

		// 通过 且无下一步骤，结束
		flowDATA.FLOW_STATUS = (hasDevManagerApproval && hasCEOApproval) ? FlowModel.STATUS.OVER : FlowModel.STATUS.REJECT;
		flowDATA.FLOW_NOW_STEP = step;
		flowDATA.FLOW_NOW_DEPT = user.USER_DEPT;
		flowDATA.FLOW_NOW_NATIVE_DEPT = user.USER_DEPT;
		flowDATA.FLOW_NOW_USER_NAME = user.USER_NAME;
		flowDATA.FLOW_NOW_USER_ID = userId;
		flowDATA.FLOW_NOW_STATE = (hasDevManagerApproval && hasCEOApproval) ? 1 : 8;
		flowDATA.FLOW_TO_DEPT = '';
		flowDATA.FLOW_TO_NATIVE_DEPT = '';
		flowDATA.FLOW_TO_STEP = -1;

		await FlowModel.edit(where, flowDATA);
		return {
			type: (hasDevManagerApproval && hasCEOApproval) ? 'over' : 'reject'
		};
	}

	// 更新申请forms信息
	async updateFlowForms(data) {
		try {
			// 确保接收到的是对象，兼容不同的调用方式
			let { id, hasImageForms, forms, userId } = data || {};
			
			console.log('[Flow] 收到更新表单请求，原始数据:', JSON.stringify(data));
			console.log('[Flow] 解析后数据 - ID:', id, '表单类型:', hasImageForms ? '图片表单' : '普通表单', '用户ID:', userId);
			
			// 数据校验
			if (!id) {
				// 尝试从整个对象中获取id
				if (data.id) {
					id = data.id;
					console.log('[Flow] 从完整对象中获取ID:', id);
				} else {
					console.error('[Flow] 更新失败: 未提供ID');
					this.AppError('流程不存在');
				}
			}
			
			// 尝试修复ID格式
			if (typeof id === 'object' && id._id) {
				id = id._id;
				console.log('[Flow] 修复ID格式为:', id);
			}
			
			// 获取流程信息
			let where = { _id: id };
			console.log('[Flow] 查询流程:', JSON.stringify(where));
			
			let flow = await FlowModel.getOne(where);
			if (!flow) {
				console.error('[Flow] 找不到要更新的流程, ID:', id);
				this.AppError('流程不存在');
			}
			
			console.log('[Flow] 找到流程:', flow._id, '标题:', flow.FLOW_OBJ?.title);
			
			// 如果提供了userId，检查权限
			if (userId) {
				let mine = (userId == flow.FLOW_USER_ID || userId == flow.FLOW_MID);
				if (!mine) {
					console.error('[Flow] 权限错误: 用户无权修改此流程');
					this.AppError('您无权修改此流程');
				}
			}
			
			// 更新流程中的表单
			let flowForms = flow.FLOW_FORMS;
			if (!flowForms || !Array.isArray(flowForms)) {
				console.error('[Flow] 流程表单格式错误');
				this.AppError('流程表单格式错误');
			}
			
			// 根据不同的表单类型进行更新
			if (hasImageForms && hasImageForms.length > 0) {
				console.log('[Flow] 更新图片表单，字段数:', hasImageForms.length);
				// 更新表单中的图片
				for (let j = 0; j < flowForms.length; j++) {
					for (let k = 0; k < hasImageForms.length; k++) {
						if (flowForms[j].mark === hasImageForms[k].mark) {
							flowForms[j].val = hasImageForms[k].val;
							console.log('[Flow] 更新字段:', hasImageForms[k].mark);
						}
					}
				}
			} else if (forms && Array.isArray(forms)) {
				console.log('[Flow] 替换整个表单');
				flowForms = forms;
			} else {
				console.error('[Flow] 未提供有效的表单数据');
				this.AppError('未提供有效的表单数据');
			}
			
			// 重新计算flowObj
			let flowObj = this._getFlowFormObj(flowForms);
			
			// 更新数据库
			let updateData = { 
				FLOW_FORMS: flowForms,
				FLOW_OBJ: flowObj
			};
			
			console.log('[Flow] 更新流程:', flow._id);
			await FlowModel.edit({ _id: id }, updateData);
			console.log('[Flow] 成功更新流程表单');
			
			return { success: true };
		} catch (err) {
			console.error('[Flow] 更新表单出错:', err);
			throw err;
		}
	}

	// 更新审批forms信息
	async updateStepForms({
		id,
		hasImageForms
	}) {
		// 获取流程信息
		let flow = await FlowModel.getOne({ _id: id });
		if (!flow) this.AppError('流程不存在');

		// 更新流程中的图片forms
		let flowList = flow.FLOW_LIST;
		if (!flowList || !Array.isArray(flowList)) return;

		for (let i = 0; i < flowList.length; i++) {
			let forms = flowList[i].forms;
			if (!forms || !Array.isArray(forms)) continue;

			// 更新流程中表单的图片
			if (hasImageForms && hasImageForms.length > 0) {
				for (let j = 0; j < forms.length; j++) {
					for (let k = 0; k < hasImageForms.length; k++) {
						if (forms[j].mark === hasImageForms[k].mark) {
							forms[j].val = hasImageForms[k].val;
						}
					}
				}
			}
		}

		// 更新数据库
		await FlowModel.edit({ _id: id }, { FLOW_LIST: flowList });
	}


	/**删除数据 */
	async delFlow(userId, id) {
		try {
			console.log('[Flow] 收到删除请求，ID:', id, '用户ID:', userId);
			
			// 数据校验
			if (!id) {
				console.error('[Flow] 删除失败: 未提供ID');
				this.AppError('单号不存在');
			}
			
			// 尝试修复ID格式
			if (typeof id === 'object' && id._id) {
				id = id._id;
				console.log('[Flow] 修复ID格式为:', id);
			}
			
			// 获取我的身份
			let user = await UserModel.getOne({ USER_MINI_OPENID: userId }, 'USER_STATUS,USER_DEPT');
			if (!user) {
				console.error('[Flow] 用户不存在:', userId);
				this.AppError('用户不存在');
			}

			// 查询流程 - 允许通过FLOW_USER_ID或FLOW_MID查询
			let where = {
				_id: id
			};
			
			// 增加OR条件，支持两种用户ID字段
			where.or = [
				{ FLOW_USER_ID: userId },
				{ FLOW_MID: userId }
			];
			
			console.log('[Flow] 删除流程查询条件:', JSON.stringify(where));
			
			let flow = await FlowModel.getOne(where);
			if (!flow) {
				console.error('[Flow] 找不到要删除的流程, ID:', id, '用户ID:', userId);
				this.AppError('流程不存在或者您无权操作');
			}

			console.log('[Flow] 找到流程:', flow._id, '状态:', flow.FLOW_STATUS);

			// 删除状态检查的限制，允许删除所有状态的流程
			// if (flow.FLOW_STATUS != FlowModel.STATUS.CREATED && flow.FLOW_STATUS != FlowModel.STATUS.REJECT) {
			//   console.error('[Flow] 流程状态不允许删除:', flow.FLOW_STATUS);
			//   this.AppError('正在审批或已通过的流程不能删除');
			// }

			let delWhere = { _id: flow._id };
			console.log('[Flow] 删除流程:', flow._id, '状态:', flow.FLOW_STATUS);
			await FlowModel.del(delWhere);
			console.log('[Flow] 成功删除流程, ID:', flow._id);
			
			return true;
		} catch (err) {
			console.error('[Flow] 删除流程出错:', err);
			throw err;
		}
	}


	/** 取得我的申请列表 */
	async getMyFlowList(userId, {
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序 
		page,
		size,
		isTotal = true,
		oldTotal
	}) {
		try {
			console.log('[Flow Service] 获取我的申请列表，用户ID:', userId);
			
			orderBy = orderBy || {
				'FLOW_ADD_TIME': 'desc'
			};
			
			let fields = 'FLOW_NO,FLOW_DEPTS,FLOW_TO_STEP,FLOW_NOW_NATIVE_DEPT,FLOW_CATE_NAME,FLOW_TO_DEPT,FLOW_NOW_USER_ID,FLOW_OBJ,FLOW_USER_DEPT,FLOW_NOW_USER_NAME,FLOW_NOW_STEP,FLOW_NOW_DEPT,FLOW_STATUS,FLOW_ADD_TIME';

			let where = {
				_pid: this.getProjectId()
			};

			// 构建基本查询条件
			where.or = [{
				FLOW_USER_ID: userId
			}, {
				FLOW_MID: userId
			}];

			if (util.isDefined(search) && search) {
				where.or = [{
					'FLOW_OBJ.person': ['like', search]
				}];
				
				// 如果search可以转为数字，则添加编号搜索条件
				if (!isNaN(search)) {
					where.or.push({
						'FLOW_NO': ['=', Number(search)]
					});
				}
			} else if (sortType && sortVal !== '') {
				switch (sortType) {
					case 'cateId': {
						where.FLOW_CATE_ID = sortVal;
						break;
					}
					case 'status': {
						where.FLOW_STATUS = Number(sortVal);
						break;
					}
					case 'sort': {
						orderBy = this.fmtOrderBySort(sortVal, 'FLOW_ADD_TIME');
						break;
					}
				}
			}

			console.log('[Flow Service] 查询条件:', JSON.stringify(where));
			console.log('[Flow Service] 排序:', JSON.stringify(orderBy));
			
			let result = await FlowModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
			
			console.log('[Flow Service] 查询成功，返回记录数:', result?.list?.length || 0);
			
			return result;
		} catch (err) {
			console.error('[Flow Service] 获取我的申请列表出错:', err);
			throw err;
		}
	}

	/** 取得待我审批的 */
	async getMyCheckingList(userId, {
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序 
		page,
		size,
		isTotal = true,
		oldTotal
	}) {
		// 检查我的身份条件
		let user = await UserModel.getOne({ USER_MINI_OPENID: userId, USER_STATUS: 1, USER_AUTH: 1 });
		if (!user) this.AppError('您没有审批权限');

		orderBy = orderBy || {
			'FLOW_ADD_TIME': 'desc'
		};
		let fields = 'FLOW_NO,FLOW_DEPTS,FLOW_TO_STEP,FLOW_NOW_NATIVE_DEPT,FLOW_CATE_NAME,FLOW_OBJ,FLOW_USER_DEPT,FLOW_NOW_USER_NAME,FLOW_NOW_STEP,FLOW_NOW_DEPT,FLOW_STATUS,FLOW_ADD_TIME';


		let where = {};
		where.and = {
			_pid: this.getProjectId(), //复杂的查询在此处标注PID  
			FLOW_STATUS: FlowModel.STATUS.RUN,
			FLOW_TO_DEPT: user.USER_DEPT
		};

		if (util.isDefined(search) && search) {
			where.or = [
				{ ['FLOW_OBJ.person']: ['like', search] },
				{ ['FLOW_NO']: Number(search) },
			];
			/*
			where.and.or
			where.and = [
				{ ['FLOW_OBJ.person']: ['like', search] }
			];*/
		} else if (sortType && sortVal !== '') {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.FLOW_CATE_ID = sortVal;
					break;
				}
				case 'status': {
					where.and.FLOW_STATUS = Number(sortVal);
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'FLOW_ADD_TIME');
					break;
				}
			}
		}
		let result = await FlowModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);


		return result;
	}

	/** 取得我已审批的 */
	async getMyCheckedList(userId, {
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序 
		page,
		size,
		isTotal = true,
		oldTotal
	}) {
		// 检查我的身份条件
		let user = await UserModel.getOne({ USER_MINI_OPENID: userId, USER_STATUS: 1, USER_AUTH: 1 });
		if (!user) this.AppError('您没有审批权限');

		orderBy = orderBy || {
			'FLOW_ADD_TIME': 'desc'
		};
		let fields = 'FLOW_NO,FLOW_DEPTS,FLOW_TO_STEP,FLOW_NOW_NATIVE_DEPT,FLOW_CATE_NAME,FLOW_TO_DEPT,FLOW_NOW_USER_ID,FLOW_OBJ,FLOW_USER_DEPT,FLOW_NOW_USER_NAME,FLOW_NOW_STEP,FLOW_NOW_DEPT,FLOW_STATUS,FLOW_ADD_TIME';

		let where = {};
		where.and = {
			_pid: this.getProjectId(), //复杂的查询在此处标注PID  
			'FLOW_LIST.userId': userId
		};


		if (util.isDefined(search) && search) {
			where.or = [
				{ ['FLOW_OBJ.person']: ['like', search] },
				{ ['FLOW_NO']: Number(search) },
			];
			/*+
			where.and.or
			where.and['FLOW_OBJ.person'] = ['like', search];*/

		} else if (sortType && sortVal !== '') {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.FLOW_CATE_ID = sortVal;
					break;
				}
				case 'status': {
					where.and.FLOW_STATUS = Number(sortVal);
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'FLOW_ADD_TIME');
					break;
				}
			}
		}
		let result = await FlowModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);

		return result;
	}

	/** 从表单中提取数据 */
	_getFlowFormObj(forms) {
		let flowObj = {
			title: '', // 标题
			desc: '', // 详情
			person: '', // 申请人 
			phone: '' // 联系电话
		};

		if (!Array.isArray(forms)) return flowObj;

		for (let k = 0; k < forms.length; k++) {
			if (forms[k].mark == 'title') flowObj.title = forms[k].val;
			if (forms[k].mark == 'desc') flowObj.desc = forms[k].val;
			if (forms[k].mark == 'person') flowObj.person = forms[k].val;
			if (forms[k].mark == 'phone') flowObj.phone = forms[k].val;
		}
		return flowObj;
	}

}

module.exports = FlowService;